package com.zhang.controller.system;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhang.common.util.result.R;
import com.zhang.common.util.result.RUtils;

import com.zhang.system.dto.RoleSearchDTO;
import com.zhang.system.entity.Role;
import com.zhang.system.service.IRoleService;
import com.zhang.system.entity.AdminUser;
import com.zhang.system.service.IAdminUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 创世神
 * @since 2023-07-03
 */
@RestController
@RequestMapping("/role/")
@SaCheckRole("admin")
@Slf4j
public class RoleController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IAdminUserService adminUserService;

    @GetMapping("getAllRoles")
    public R getAllRoles() {
        List<Role> list = roleService.list();
        return RUtils.successData(list);
    }
    @GetMapping("search")
    public R searchRoles(RoleSearchDTO roleSearchDTO) {
        Page<Role> page = roleService.searchRoles(roleSearchDTO);
        return RUtils.successData(page);
    }
    @GetMapping("getRole")
    public R getRole(@RequestParam Long roleId) {
        Role role = roleService.getById(roleId);
        return RUtils.successData(role);
    }

    @PutMapping("updateRole")
    public R updateRole(@RequestBody Role role) {
        boolean b = roleService.updateById(role);
        return b ? RUtils.successMsg("修改成功") : RUtils.err("修改失败");
    }

    @PostMapping("addRole")
    public R addRole(@RequestBody Role role) {
        String now = DateUtil.now();
        AdminUser userInfo = adminUserService.getUserInfo(StpUtil.getLoginIdAsLong());
        role.setCreateBy(userInfo.getUserName());
        role.setCreateTime(now);
        boolean b = roleService.save(role);
        return b ? RUtils.successMsg("新增成功") : RUtils.err("新增失败");
    }

    @DeleteMapping("{roleId}")
    public R deleteRole(@PathVariable String  roleId) {
        boolean b = roleService.removeById(roleId);
        return b ? RUtils.successMsg("删除成功") : RUtils.err("删除失败");
    }
}
